package com.dawn.module.mp.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.framework.common.util.json.JsonUtils;
import com.dawn.framework.web.core.util.RequestUtils;
import com.dawn.module.mp.framework.mp.core.MpServiceFactory;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: cnsu-cmh
 * @time: 2024/8/8 12:08
 */
@Tag(name = "微信公众号 APP - AccessToken")
@RestController
@RequestMapping("/mp/access-token")
@Slf4j
public class AccessTokenController {

    @Resource
    @Lazy // 延迟加载，解决循环依赖的问题
    private MpServiceFactory mpServiceFactory;

    @RequestMapping(value = "/get")
    @Operation(summary = "获取微信公众号AccessToken")
    @PermitAll
    public CommonResult getAccessToken(HttpServletRequest request) {
        JSONObject params = RequestUtils.getReqParamJSON(request);
        String appid = params.getString("appid");
        log.warn("---------获取微信公众号AccessToken-------appid:"+ appid);
        WxMpService wxService = mpServiceFactory.getRequiredMpService(appid);
        wxService.switchover(appid);
        List<WxMpTemplate> wxMpTemplateList = new ArrayList<>();
        String accessToken = "";
        try {
            wxMpTemplateList = wxService.getTemplateMsgService().getAllPrivateTemplate();
            if(wxMpTemplateList!=null && wxMpTemplateList.size() > 0){
                log.warn("---------获取微信公众号AccessToken 模板消息-------wxMpTemplateList："+ wxMpTemplateList.size());
                accessToken = wxService.getAccessToken();
            }else {
                log.warn("---------获取微信公众号AccessToken 过期强制刷新-------");
                accessToken = wxService.getAccessToken(true);
            }
            log.warn("---------获取微信公众号AccessToken-------accessToken:"+accessToken);
            return CommonResult.success(accessToken);
        } catch (WxErrorException e) {
            log.warn("---------获取微信公众号AccessToken异常-------Exception:"+ e.getMessage());
            return CommonResult.error(-1,e.getMessage());
        }

    }

}
